import React from 'react';
import styles from './index.less';
import { Spin, Space, Button, DatePicker, Select } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import { connect } from 'umi';

import { TRDefault, TRMessage } from '#/components';
import { UploadOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import { PageLoading } from '@/components';
import { useExcel } from '@/hooks';
import { useTRState, TjStation, TjSelect, TjTable } from '@/pages/ETrade/components';
import { getTreeByCodes } from '@/utils/index.js';

import { queryMarketList, getAllFieldList, getSpotExpensesSummaryList } from './services.js';
import { default as SpotMonthModal } from './modal/index';
import { getColumns } from './helper';

const getDateRange = () => {
  // 当前日期>2号，默认为当月1日至当前日
  // 当前日期<=2号，默认为前一自然月整月
  const today = new Date().getDate();
  if (today > 2) {
    return [moment().startOf('month'), moment()];
  }
  return [moment().add(-1, 'months').startOf('month'), moment().add(-1, 'months').endOf('month')];
};

const spotExpensesSummary = (props) => {
  /** data */
  const { menuCode, buttonPermissions } = props;
  const [state, setState] = useTRState({
    canExport: buttonPermissions.some((item) => item.menuCode === 'spotExpensesSummaryExport'),
    canEditMonths: buttonPermissions.some((item) => item.menuCode === 'SpotMonthLabel'),
    // 初始化三件套
    spinning: true,
    error: '',
    power: [],
    // 表单
    regionItem: null,
    stationIdList: [],
    tableHeadList: [],
    dates: getDateRange(),
    regionName: '',
    // 数据
    loading: true,
    loadingField: false,
    fieldOptions: [],
    tableColumns: [],
    tableData: [],
    visible: false,
  });

  React.useEffect(() => {
    init();
  }, []);

  /** apis */
  const init = async () => {
    // 权限
    const res = await queryMarketList(menuCode);
    let power = [];
    let error = '';
    if (res?.statusCode === HttpCode.SUCCESS) {
      const { treeOptions } = getTreeByCodes(['market', 'group', 'station'], res.json);
      power = treeOptions;
    } else {
      error = res?.message || '系统异常';
    }
    setState({
      power,
      error,
      spinning: false,
    });
    power?.[0] && onChangeRegion(power[0], 'search');
  };
  const fetchFields = async (t) => {
    setState({ loadingField: true });
    const _params = {
      stationIdList: state.stationIdList,
      startDate: state.dates[0].format('YYYY-MM-DD'),
      endDate: state.dates[1].format('YYYY-MM-DD'),
    };
    const res = await getAllFieldList(_params);
    const fieldOptions = res?.resultList || [];
    const tableHeadList = fieldOptions.map((x) => x.value);
    state.tableHeadList = tableHeadList;
    setState({
      fieldOptions,
      tableHeadList,
      loadingField: false,
    });
    t === 'search' && _onFinish();
  };

  /** methods */
  const onChangeRegion = (regionItem, t) => {
    // 切换省份,全选交易单元
    state.regionItem = regionItem;
    const list = regionItem?.children || [];
    const stations = _.flatten(list.map(({ children }) => children));
    const allId = stations.map((x) => x.value);
    setState({ regionItem });
    onChangeStation(allId, t);
  };

  const onChangeStation = async (stationIdList, t) => {
    // 改变交易单元,查询费用类型
    state.stationIdList = stationIdList;
    setState({ stationIdList });
    fetchFields(t);
  };
  const onChangeDates = (dates) => {
    state.dates = dates;
    setState({ dates });
    fetchFields();
  };

  const _onFinish = async () => {
    // 查询
    setState({
      regionName: state.regionItem.market,
      loading: true,
    });
    const params = {
      stationIdList: state.stationIdList,
      tableHeadList: state.tableHeadList,
      startDate: state.dates[0].format('YYYY-MM-DD'),
      endDate: state.dates[1].format('YYYY-MM-DD'),
    };
    const res = await getSpotExpensesSummaryList(params);
    const dataHead = res?.dataHead || [];
    const tableData = res?.dataList || [];
    const tableColumns = getColumns(dataHead, tableData);
    setState({
      tableColumns,
      tableData,
      loading: false,
    });
  };

  const _onReset = () => {
    // 重置&查询
    const dates = getDateRange();
    state.dates = dates;
    setState({
      dates,
    });
    onChangeRegion(state.power?.[0], 'search');
  };

  const _onExport = () => {
    // 导出
    if (!state.canExport) return TRMessage.info('请联系管理员获取相关权限');
    useExcel({
      filename: '现货出清结果',
      columns: state.tableColumns,
      data: state.tableData,
      merges: ['groupName', 'provinceName', 'stationName', 'actualQuantity'],
    });
  };

  /** render */
  const _renderForm = () => {
    return (
      <Space size={16} wrap>
        <Select
          style={{ width: 160 }}
          value={state.regionItem?.value}
          options={state.power}
          optionFilterProp="label"
          showSearch
          showArrow
          onChange={(v, opt) => onChangeRegion(opt)}
        />
        <TjStation
          value={state.stationIdList}
          options={state.regionItem?.children}
          onChange={onChangeStation}
        />
        <DatePicker.RangePicker
          style={{ width: 256 }}
          value={state.dates}
          separator="-"
          format={'YYYYMMDD'}
          allowClear={false}
          onChange={onChangeDates}
        />
        <TjSelect
          label="费用类型"
          value={state.tableHeadList}
          options={state.fieldOptions}
          onChange={(tableHeadList) => setState({ tableHeadList })}
          mode="multiple"
          style={{ width: 360 }}
          disabled={state.loadingField}
        />
        <Space size={16}>
          <Button style={{ width: 98, height: 32 }} type="primary" onClick={_onFinish}>
            查询
          </Button>
          <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
            重置
          </Button>
        </Space>
      </Space>
    );
  };

  const _renderMain = () => {
    if (state.loading) return null;
    if (!state.tableData?.length) return <TRDefault type="empty" />;
    return (
      <div className={styles.flexcolumn}>
        <div className={styles.title}>{state.regionName}现货费用汇总报表</div>
        <div className={styles.table}>
          <TjTable columns={state.tableColumns} dataSource={state.tableData} useVirtual={false} />
        </div>
      </div>
    );
  };

  if (state.spinning) return <PageLoading />;
  if (state.error) return <TRDefault type="error" message={state.error} />;
  if (!state.power?.length) return <TRDefault type="lock" />;
  return (
    <Spin spinning={state.loading}>
      <div className={styles.content}>
        <div className={styles.head}>
          <div>{_renderForm()}</div>
          <Space size={16} wrap>
            <SpotMonthModal disabled={!state.canEditMonths} />
            <Button
              style={{ padding: 0 }}
              type="link"
              icon={<UploadOutlined />}
              onClick={_onExport}
            >
              导出
            </Button>
          </Space>
        </div>
        <div className={styles.main}>
          <div className={styles.box}>{_renderMain()}</div>
        </div>
      </div>
    </Spin>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(spotExpensesSummary);
